// 导入
import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建axios实例
const instance = axios.create({
    baseURL: 'http://localhost:8083',  // 修改为实际的后端地址
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器
instance.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token')
        const user = localStorage.getItem('user')
        const roleId = localStorage.getItem('roleId')
        const requestId = `${config.method}-${config.url}-${Date.now()}`
        config.requestId = requestId

        // 详细的存储状态日志
        console.group(`请求 ${requestId} 的token检查`)
        console.log('存储状态:', {
            url: config.url,
            hasToken: !!token,
            tokenLength: token ? token.length : 0,
            hasUser: !!user,
            roleId: roleId
        })

        // 对于不需要token的路由，直接放行
        const publicPaths = ['/login', '/register', '/captcha']
        if (publicPaths.some(path => config.url.includes(path))) {
            console.log('✅ 公共路径，无需token验证')
            console.groupEnd()
            return config
        }

        // token存在性检查
        if (!token) {
            console.warn('❌ token不存在，即将跳转登录页')
            console.groupEnd()
            handleTokenError('token不存在')
            return Promise.reject('未登录')
        }

        try {
            // JWT格式检查
            const tokenParts = token.split('.')
            if (tokenParts.length !== 3) {
                console.error('❌ token格式无效:', {
                    length: token.length,
                    parts: tokenParts.length
                })
                console.groupEnd()
                handleTokenError('token格式无效')
                return Promise.reject('无效的token格式')
            }

            // token有效，添加到请求头
            config.headers['token'] = token
            console.log('✅ token验证通过，已添加到请求头')
            console.groupEnd()
            return config
        } catch (error) {
            console.error('❌ token处理出错:', error)
            console.groupEnd()
            handleTokenError('token处理出错')
            return Promise.reject('Token处理错误')
        }
    },
    error => {
        console.error('❌ 请求拦截器错误:', error)
        console.groupEnd()
        return Promise.reject(error)
    }
)

// 响应拦截器
instance.interceptors.response.use(
    response => {
        const requestId = response.config.requestId
        console.group(`响应 ${requestId} 的状态检查`)
        console.log('响应数据:', {
            url: response.config.url,
            status: response.status,
            code: response.data.code,
            msg: response.data.msg,
            hasToken: !!localStorage.getItem('token')
        })

        // token相关错误检查
        if (response.data.code === 401 || 
            (response.data.message && response.data.message.includes('token')) ||
            (response.data.msg && response.data.msg.includes('token'))) {
            console.warn('❌ 响应指示token无效:', {
                code: response.data.code,
                msg: response.data.msg
            })
            console.groupEnd()
            handleTokenError('响应指示token无效')
            return Promise.reject(response.data)
        }

        // 成功响应
        if (response.data.code === 200) {
            console.log('✅ 请求成功')
            console.groupEnd()
            return response
        }

        // 其他错误
        console.warn('⚠️ 请求失败:', response.data.msg)
        console.groupEnd()
        const errorMsg = response.data.message || response.data.msg || '请求失败'
        ElMessage.error(errorMsg)
        return Promise.reject(response.data)
    },
    error => {
        const requestId = error.config?.requestId
        console.group(`错误响应 ${requestId} 的处理`)
        console.error('响应错误:', {
            url: error.config?.url,
            status: error.response?.status,
            data: error.response?.data
        })

        // 401错误检查
        if (error.response?.status === 401 || 
            (error.response?.data?.message && error.response?.data?.message.includes('token')) ||
            (error.response?.data?.msg && error.response?.data?.msg.includes('token'))) {
            console.warn('❌ Token验证失败')
            console.groupEnd()
            handleTokenError('HTTP状态码为401或token相关错误')
            return Promise.reject(error)
        }

        // 其他错误
        console.warn('⚠️ 其他错误')
        console.groupEnd()
        const errorMsg = error.response?.data?.message || 
                        error.response?.data?.msg || 
                        error.message || 
                        '请求失败'
        ElMessage.error(errorMsg)
        return Promise.reject(error)
    }
)

// 处理token错误
const handleTokenError = (reason) => {
    if (window._handlingTokenError) {
        console.log('⚠️ 已在处理token错误，跳过重复处理')
        return
    }
    window._handlingTokenError = true

    console.group('Token错误处理')
    console.log('错误原因:', reason)
    console.log('当前状态:', {
        path: window.location.pathname,
        token: localStorage.getItem('token') ? '存在' : '不存在',
        user: localStorage.getItem('user') ? '存在' : '不存在',
        roleId: localStorage.getItem('roleId')
    })
    
    // 保存当前路径
    const currentPath = window.location.pathname
    if (currentPath !== '/login') {
        localStorage.setItem('lastPath', currentPath)
    }
    
    // 清除用户信息
    clearUserInfo()
    
    // 跳转到登录页
    if (window.location.pathname !== '/login') {
        console.log('🔄 即将跳转到登录页...')
        setTimeout(() => {
            window.location.href = '/login'
            setTimeout(() => {
                window._handlingTokenError = false
                console.groupEnd()
            }, 1000)
        }, 100)
    } else {
        window._handlingTokenError = false
        console.groupEnd()
    }
}

// 清除用户信息
const clearUserInfo = () => {
    const storageInfo = {}
    const keys = ['token', 'user', 'roleId', 'id']
    
    // 先收集信息
    keys.forEach(key => {
        const value = localStorage.getItem(key)
        storageInfo[key] = key === 'token' ? 
            (value ? '(token存在)' : '(无token)') : 
            (value || '(空)')
    })
    
    console.log('清除前的存储信息:', storageInfo)
    
    // 然后清除
    keys.forEach(key => {
        localStorage.removeItem(key)
    })
    
    console.log('用户信息已清除')
}

export default instance
